import { ChangeDetectorRef, ElementRef, Injector, Renderer2 } from '@angular/core';
import * as _ from 'lodash';
import { ActivatedRoute, Router } from '@angular/router';
import { differenceInCalendarDays } from 'date-fns';
import { NzMessageService } from 'ng-zorro-antd/message';
import { WebStorageService } from '../services/webStorage.service';

export abstract class BaseUI {
    sortName: string = null; //需要排序的名称
    sortValue: string = null; //需要排序的值
    listOfSearchName: Array<any> = []; //从排序列表中搜索排序的名称
    tableCheckeds: Array<any> = []; //表格全部选中的值
    tableAllCheckedState = false; //表格中值是否被选中状态
    indeterminate = false; //表格顶部的checkbox选中和未选中的状态
    batchButtonState = true; //批量操作按钮的状态
    searchPanelState = false; //搜索面板状态
    renderer2: Renderer2;
    changeDetectorRef: ChangeDetectorRef;
    router: Router;
    activatedRoute: ActivatedRoute;
    messageService: NzMessageService;
    el: ElementRef;
    webStorageService: WebStorageService;
    title = "管理系统";
    protected constructor(private _baseInjector: Injector) {
        this.renderer2 = this._baseInjector.get(Renderer2);
        this.el = this._baseInjector.get(ElementRef);
        this.changeDetectorRef = this._baseInjector.get(ChangeDetectorRef);
        this.router = this._baseInjector.get(Router);
        this.activatedRoute = this._baseInjector.get(ActivatedRoute);
        this.messageService = this._baseInjector.get(NzMessageService);
        this.webStorageService = this._baseInjector.get(WebStorageService);
    }
    /**
     * 刷新选中状态
     * @private
     */
    onRefreshTableCheckState(dataArray: Array<any>) {
        const allChecked = dataArray.every((value) => value.checked === true);
        const allUnChecked = dataArray.every((value) => !value.checked);
        this.tableAllCheckedState = allChecked;
        this.indeterminate = !allChecked && !allUnChecked;
        this.batchButtonState = !dataArray.some((value) => value.checked);
        this.tableCheckeds = dataArray.filter((value) => value.checked);
    }

    /**
     * 选中所有的项
     * @param value
     * @param dataArray
     */
    onTableCheckAll(value: any, dataArray: Array<any>) {
        if (value) {
            dataArray.forEach((data) => (data.checked = true));
        } else {
            dataArray.forEach((data) => (data.checked = false));
        }
        this.onRefreshTableCheckState(dataArray);
    }

    /**
     * 表格排序
     */
    tableSort(sort: { key: string; value: string }, dataArray: Array<any>) {
        this.sortName = sort.key;
        this.sortValue = sort.value;
        this.tableSortFilter(dataArray);
    }

    /**
     * 表格排序过滤
     */
    tableSortFilter(dataArray: Array<any>) {
        const filterFunc = (item) =>
            this.listOfSearchName.length ? this.listOfSearchName.some((name) => item.name.indexOf(name) !== -1) : true;
        const data = dataArray.filter((item) => filterFunc(item));
        if (this.sortName) {
            dataArray = data.sort((a, b) =>
                this.sortValue === 'ascend' ? (a[this.sortName] > b[this.sortName] ? 1 : -1) : b[this.sortName] > a[this.sortName] ? 1 : -1
            );
            return dataArray;
        } else {
            return data;
        }
    }

    /**
     * 获取表格的实际宽度
     */
    getTableWidth(): string {
        let tableWidth = 0;
        setTimeout(() => {
            const tableRow = this.renderer2.selectRootElement('.ant-table-row ', true);
            _.forEach(tableRow.childNodes, (item) => {
                tableWidth += Number(item.attributes.nzWidth.value.slice(0, item.attributes.nzWidth.value.indexOf('p')));
            });
            this.changeDetectorRef.detectChanges();
        }, 100);
        return tableWidth + 'px';
    }

    /**
     * 保存需要返回的路由地址
     * @param level 跳转的层级
     */
    saveBackUrl(level: number) {
        if (level === 1) {
            sessionStorage.setItem('backUrl', JSON.stringify(this.router.url));
        } else {
            sessionStorage.setItem('secondBackUrl', JSON.stringify(this.router.url));
        }
    }

    /**
     * 返回上一页
     * * @param level 跳转的层级
     */
    onBack(level: number) {
        if (level === 1) {
            if (sessionStorage.getItem('backUrl')) {
                const backUrl = JSON.parse(sessionStorage.getItem('backUrl'));
                this.router.navigateByUrl(backUrl);
            }
        } else {
            if (sessionStorage.getItem('secondBackUrl')) {
                const backUrl = JSON.parse(sessionStorage.getItem('secondBackUrl'));
                this.router.navigateByUrl(backUrl);
            }
        }
    }

    /**
     * 被禁用的日期：当前日期之后的都会被禁用
     */
    getBeforeDisabledDate() {
        return (current: Date): boolean => {
            return differenceInCalendarDays(current, new Date()) > 0;
        };
    }

    /**
     * 被禁用的日期：当前日期之前的都会被禁用
     */
    getAfterDisabledDate(date: Date) {
        return (current: Date): boolean => {
            return differenceInCalendarDays(current, date) < 0;
        };
    }

    /**
     * 获取当前的路由地址
     */
    getRouterUrl() {
        return this.router.url.includes('?') ? this.router.url.split('?')[0] : this.router.url;
    }

    /**
     * 显示全局消息
     * @param type 类型：success、error、info、warning、loading
     * @param content 显示的文字内容
     */
    showMessage(type: string, content: string) {
        this.messageService.create(type, content);
    }
}
